package com.gator.mybatis.executor;

import com.gator.mybatis.entity.User;


import java.sql.*;

/**
 * @Authror PABLO
 * @Date 2022/4/26 21:26
 * @Desc 执行核心类
 */
public class Executor<T> {


    public T query(String sql, Object param) {

        User user = new User();
        Connection c = null;
        PreparedStatement p = null;
        ResultSet r = null;
        try {
            //加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //获得连接对象
            c = DriverManager.getConnection("jdbc:mysql://localhost:3306/my_sql_learn", "root", "123456");
            //获得编译语句对象
            p = c.prepareStatement(sql);
            //在？占位符上设置参数
            p.setInt(1, (Integer) param);
            //语句对象查询获得结果集
            r = p.executeQuery();
            //遍历结果集
            while (r.next()) {
                Integer id = r.getInt("id");
                Integer age = r.getInt("age");
                String name = r.getString("name");
                user.setId(id);
                user.setAge(age);
                user.setName(name);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放资源
            try {
                r.close();
                p.close();
                c.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return (T) user;
    }
}
